package wh.coach.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

public class HttpWrite {

    public static void sendHttpRequest(String url, String folder, String path, BufferControl BufferSize) throws Exception {
        OkHttpClient client = new OkHttpClient();

        String property = System.getProperty("user.home");
        File folderPath = new File(property, folder);
        folderPath.mkdir();
        File file = new File(folderPath, path);

        Request request = new Request.Builder()
                .url(url)
                .method("GET", null)
                .build();

        try (Response response = client.newCall(request).execute()) {
            if (response.isSuccessful()) {
                ResponseBody responseBody = response.body();
                if (responseBody != null) {
                    try (InputStream inputStream = responseBody.byteStream();
                         OutputStream outputStream = new FileOutputStream(file, true)) {

                        byte[] buffer = new byte[BufferSize.getBufferSize()];
                        int bytesRead;
                        while ((bytesRead = inputStream.read(buffer)) != -1) {
                            outputStream.write(buffer, 0, bytesRead);
                        }

                        System.out.println("成功保存到：" + file.getAbsolutePath());
                    }
                } else {
                    throw new Exception("没东西读");
                }
            } else {
                throw new Exception("出错了");
            }
        }
    }

    //设置缓冲大小接口
    public interface BufferControl {
        int getBufferSize();
    }

    public static class FixedBuffer implements BufferControl {

        private final int bufferSize;

        public FixedBuffer(int bufferSize) {
            this.bufferSize = bufferSize;
        }

        @Override
        public int getBufferSize() {
            return bufferSize;
        }
    }

}
